package com.ruyuan.seckilling.purchase.async.listener;

import com.ruyuan.seckilling.common.CacheKey;
import com.ruyuan.seckilling.purchase.async.BasePurchaseListener;
import com.ruyuan.seckilling.purchase.async.PurchaseContext;
import com.ruyuan.seckilling.purchase.async.event.Step2CheckUser;
import com.ruyuan.seckilling.purchase.async.event.Step3LockStock;
import com.ruyuan.starter.async.anno.Channel;
import com.ruyuan.starter.async.event.BaseEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 校验用户的抢购次数，最多允许用户抢购3次
 *
 * @author zhonghuashishan
 */
@Slf4j
@Component
@Channel("step2")
public class Step2Listener extends BasePurchaseListener<Step2CheckUser> {

    @Override
    public boolean accept(BaseEvent event) {
        return event instanceof Step2CheckUser;
    }

    @Override
    protected void doThisStep(Step2CheckUser event, PurchaseContext purchaseContext) {
        executorService.execute("step2", () -> {
            Long activity = purchaseContext.getActivityId();
            Long userId = purchaseContext.getUserId();
            String key = CacheKey.buildCheckUserKey(activity, userId);
            Long incr = cacheSupport.incr(key);
            if (incr <= 3) {
                // 算上这次抢购用户参与抢购的次数在3次以内，满足条件，进入下一步开始扣减库存
                cacheSupport.expire(key, 600);
                log.info("校验用户的抢购次数，用户抢购次数在3次以内");
                bossEventBus.publish("step3", new Step3LockStock(), purchaseContext);
                return;
            }
            response(purchaseContext.getAsyncContext(), false, "已经超过最大的抢购次数了");
        });
    }
}
